import type { Context, Next } from "koa";
import type { JWTPayload } from "../services/vendor/jsonwebtoken";
import { container } from "@/services/register";
import { HttpException } from "@/error/exception";

export default (permissions: string[]) => {
  return async (ctx: Context, next: Next) => {
    // const { userId } = ctx.state.user as JWTPayload;
    // const permissionNames = await container
    //   .resolve("RedisUserService")
    //   .getUserPermission(userId);

    // const isRoot = userId === 1;

    // if (!isRoot && permissionNames.length === 0) {
    //   throw new HttpException("无权访问", 403);
    // }

    // // 动态权限检测
    // const hasUserPermission = (permissions: string[]) => {
    //   return (
    //     isRoot ||
    //     Boolean(permissionNames.find((pn) => permissions.includes(pn)))
    //   );
    // };

    // if (!hasUserPermission(permissions)) {
    //   throw new HttpException("无权访问", 403);
    // }

    // // 将缓存用户权限列表附加到请求对象上
    // ctx.state.hasUserPermission = hasUserPermission;

    await next();
  };
};
